@*
    职级管理添加/编辑页面
*@
@{
    ViewData["Title"] = "职级管理";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@ViewData["Title"]</title>
    <link href="~/layui/css/layui.css" rel="stylesheet" />
    <style>
        .layui-form-item .layui-input-inline {
            width: 180px;
        }
        .form-container {
            padding: 20px;
            max-width: 700px;
            margin: 0 auto;
        }
        .salary-range-hint {
            color: #999;
            font-size: 12px;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    @Html.AntiForgeryToken()
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">
                <span id="pageTitle">新增职级</span>
            </div>
            <div class="layui-card-body">
                <div class="form-container">
                    <form class="layui-form" lay-filter="positionLevelForm" id="positionLevelForm">
                        <input type="hidden" name="id" id="positionLevelId">
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">职级编码</label>
                            <div class="layui-input-block">
                                <div class="layui-input-inline" style="width: 280px;">
                                    <input type="text" name="jobGradeCoding" lay-verify="jobGradeCoding" placeholder="请输入职级编码" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-input-inline" style="width: 80px;">
                                    <input type="checkbox" name="autoGenCode" lay-skin="switch" lay-text="自动|手动" lay-filter="autoGenCode">
                                </div>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">职级层次</label>
                            <div class="layui-input-block">
                                <input type="text" name="jobGradeLevel" lay-verify="jobGradeLevel" placeholder="请输入职级层次" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">职级名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="jobGradeLevelName" lay-verify="jobGradeLevelName" placeholder="请输入职级层次名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">薪资下限</label>
                            <div class="layui-input-block">
                                <input type="number" name="salaryRangelower" lay-verify="salaryRangelower" placeholder="请输入薪资范围下限" autocomplete="off" class="layui-input" min="0" step="100">
                                <div class="salary-range-hint">单位：元/月</div>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">薪资上限</label>
                            <div class="layui-input-block">
                                <input type="number" name="salaryRangelimits" lay-verify="salaryRangelimits" placeholder="请输入薪资范围上限" autocomplete="off" class="layui-input" min="0" step="100">
                                <div class="salary-range-hint">单位：元/月，必须大于等于薪资下限</div>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">备注</label>
                            <div class="layui-input-block">
                                <textarea name="referenceColumn" placeholder="请输入备注" class="layui-textarea"></textarea>
                            </div>
                        </div>
                        
                        <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
                            <button type="button" class="layui-btn" lay-submit lay-filter="submitForm">保存</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="~/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.jquery;

            // 获取URL参数
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            }

            // 判断是否为编辑模式
            var positionLevelId = getUrlParam('id');
            var isEdit = positionLevelId != null;
            var positionLevelData = null;

            // 设置页面标题
            if (isEdit) {
                $('#pageTitle').text('编辑职级');
                $('#positionLevelId').val(positionLevelId);
                loadPositionLevelData(positionLevelId);
            } else {
                $('#pageTitle').text('新增职级');
            }

            // 加载职级数据
            function loadPositionLevelData(id) {
                var loadIndex = layer.load();
                $.ajax({
                    url: '/PositionLevel/GetPositionLevel',
                    type: 'GET',
                    data: { id: id },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            positionLevelData = res.data;
                            bindFormData(positionLevelData);
                        } else {
                            layer.msg('获取职级数据失败: ' + res.message);
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        console.error('获取职级数据错误:', xhr);
                        layer.msg('服务器错误: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                    }
                });
            }

            // 绑定表单数据
            function bindFormData(data) {
                // 先设置表单值
                form.val('positionLevelForm', data);
                
                // 重新渲染表单组件
                setTimeout(function() {
                    form.render();
                }, 100);
            }

            // 自定义验证规则
            form.verify({
                jobGradeCoding: function(value) {
                    if (!value) {
                        return '职级编码不能为空';
                    }
                    if (value.length < 2) {
                        return '职级编码长度不能少于2位';
                    }
                    if (!/^[A-Za-z0-9]+$/.test(value)) {
                        return '职级编码只能包含字母和数字';
                    }
                },
                jobGradeLevel: function(value) {
                    if (!value) {
                        return '职级层次不能为空';
                    }
                    if (value.length > 50) {
                        return '职级层次长度不能超过50个字符';
                    }
                },
                jobGradeLevelName: function(value) {
                    if (!value) {
                        return '职级名称不能为空';
                    }
                    if (value.length > 100) {
                        return '职级名称长度不能超过100个字符';
                    }
                },
                salaryRangelower: function(value) {
                    if (!value) {
                        return '薪资下限不能为空';
                    }
                    if (isNaN(value) || parseFloat(value) < 0) {
                        return '薪资下限必须是大于等于0的数字';
                    }
                },
                salaryRangelimits: function(value) {
                    if (!value) {
                        return '薪资上限不能为空';
                    }
                    if (isNaN(value) || parseFloat(value) < 0) {
                        return '薪资上限必须是大于等于0的数字';
                    }
                    var lowerValue = parseFloat($('input[name="salaryRangelower"]').val());
                    var upperValue = parseFloat(value);
                    if (upperValue < lowerValue) {
                        return '薪资上限不能小于薪资下限';
                    }
                }
            });

            // 实时验证薪资范围
            $('input[name="salaryRangelower"], input[name="salaryRangelimits"]').on('blur', function() {
                var lowerValue = parseFloat($('input[name="salaryRangelower"]').val());
                var upperValue = parseFloat($('input[name="salaryRangelimits"]').val());
                
                if (!isNaN(lowerValue) && !isNaN(upperValue) && upperValue < lowerValue) {
                    layer.tips('薪资上限不能小于薪资下限', 'input[name="salaryRangelimits"]', {
                        tips: [1, '#FF5722']
                    });
                }
            });

            // 表单提交
            form.on('submit(submitForm)', function (formData) {
                var loadIndex = layer.load();
                var url, postData;
                
                postData = formData.field;
                
                if (isEdit) {
                    url = '/PositionLevel/UpdatePositionLevel';
                    postData.id = positionLevelData.id;
                } else {
                    url = '/PositionLevel/CreatePositionLevel';
                    delete postData.id;
                }
                
                // 移除自动生成开关字段
                delete postData.autoGenCode;
                
                // 转换数字字段
                postData.salaryRangelower = parseFloat(postData.salaryRangelower);
                postData.salaryRangelimits = parseFloat(postData.salaryRangelimits);
                if (isEdit) {
                    postData.id = parseInt(postData.id);
                }

                console.log("提交数据:", url, postData);

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: {
                        ...postData,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            layer.msg('操作成功', {
                                icon: 1,
                                time: 2000
                            }, function() {
                                // 返回列表页面或关闭窗口
                                if (window.parent && window.parent.layer) {
                                    window.parent.layer.closeAll();
                                    if (window.parent.layui && window.parent.layui.table) {
                                        window.parent.layui.table.reload('positionLevelTable');
                                    }
                                } else {
                                    window.location.href = '/PositionLevel/Index';
                                }
                            });
                        } else {
                            layer.msg('操作失败: ' + res.message);
                        }
                    },
                    error: function (xhr) {
                        console.error('提交请求错误:', xhr);
                        layer.close(loadIndex);
                        layer.msg('服务器错误: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                    }
                });
                return false;
            });

            // 取消按钮
            $('#cancelBtn').on('click', function () {
                if (window.parent && window.parent.layer) {
                    window.parent.layer.closeAll();
                } else {
                    window.location.href = '/PositionLevel/Index';
                }
            });

            // 监听自动生成编码开关
            form.on('switch(autoGenCode)', function(data) {
                if (data.elem.checked) {
                    // 自动生成编码
                    $.ajax({
                        url: '/PositionLevel/GenerateJobGradeCoding',
                        type: 'GET',
                        success: function(res) {
                            if (res.success) {
                                form.val('positionLevelForm', {
                                    'jobGradeCoding': res.code
                                });
                            }
                        },
                        error: function(xhr) {
                            console.error('获取编码请求错误:', xhr);
                            layer.msg('获取编码失败: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                        }
                    });
                }
            });
        });
    </script>
</body>
</html> 